package com.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.demo.model.Message;
import com.demo.service.MessageService;

@Controller
public class MessageController {

	@Autowired
	private MessageService messageService;

	// public void save(String content) {
	// Message message = new Message();
	// message.setContent(content);
	// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd
	// HH:mm:ss");
	// message.setCreateTime(formatter.format(LocalDateTime.now()));
	// messageService.save(message);
	// }
	@RequestMapping("/message/list.htm")
	public String list(Model model) {
		List<Message> messages = messageService.getMessages();
		model.addAttribute("messages", messages);
		return "message/list";
	}

	@RequestMapping("/message/input.htm")
	public String input(@RequestParam(value = "id", required = false, defaultValue = "0") Long id 
, Model model) {
		if (id > 0) {
			Message message = messageService.getMessageById(id);
			model.addAttribute("message", message);
		}
		return "message/input";
	}

	@RequestMapping("/message/update.htm")
	public String update(Message message) {
		messageService.updateMessage(message);
		return "redirect:/message/list.htm";
	}

	@RequestMapping("/message/delete.htm")
	public String delete(Long id) {
		messageService.deleteMessage(id);
		return "redirect:/message/list.htm";
	}
}
